﻿Imports System.Collections.Specialized
Imports Microsoft.TeamFoundation.Client
Imports Microsoft.TeamFoundation.WorkItemTracking.Client
Imports System.Windows.Media.Animation
Imports System.Windows.Threading
Imports System.IO

Class MainWindow

    Private ItemWrappers As ItemCollection = Application.ItemWrappers

    Public Shared ReadOnly ChangeSkinCommand As RoutedCommand = New RoutedCommand("ChangeSkin", GetType(MainWindow))
    Public Shared ReadOnly ChangeTeamServerCommand As RoutedCommand = New RoutedCommand("ChangeTeamServer", GetType(MainWindow))
    Public Shared ReadOnly ChangeTeamProjectCommand As RoutedCommand = New RoutedCommand("ChangeTeamProject", GetType(MainWindow))
    Public Shared ReadOnly SelectStoredQueryCommand As RoutedCommand = New RoutedCommand("SelectStoredQuery", GetType(MainWindow))
    Public Shared ReadOnly DisplayByCommand As RoutedCommand = New RoutedCommand("DisplayBy", GetType(MainWindow))

    Public Sub New()
        ' This call is required by the Windows Form Designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        Me.WorkingUserControl.Window = Me
        BuildSkinsMenu()
        ShowWelcomeScreen()
        BuildTeamServerMenu()
        BuildProjectsMenu()
        BuildStoredQueryMenu()
        BuildDisplayByMenu()


        '' Icon bit
        'Dim iconStream As New MemoryStream()
        'My.Resources.RDIcon.Save(iconStream)
        'iconStream.Seek(0, SeekOrigin.Begin)
        'Me.Icon = BitmapFrame.Create(iconStream)
    End Sub

#Region " Menus "

    ''' <summary>
    ''' Builds the Skins Menu
    ''' </summary>
    Private Sub BuildSkinsMenu()
        Dim skins As NameValueCollection = Application.Skins
        For Each skinName As String In skins.AllKeys
            Dim skin As MenuItem = New MenuItem()
            skin.Header = skinName
            skin.CommandParameter = skins(skinName)
            skin.Command = ChangeSkinCommand
            SkinsMenu.Items.Add(skin)
        Next
    End Sub

    ''' <summary>
    ''' Builds the Team Server list menu
    ''' </summary>
    Private Sub BuildTeamServerMenu()
        ' Clear existing menu items
        ConnectMenu.Items.Clear()
        '' Add the recent files to the menu as menu items
        For Each svr As TeamFoundationServer In RegisteredServers.GetServers
            Dim item As MenuItem = New MenuItem()
            item.Header = svr.Name
            item.CommandParameter = svr
            item.Command = ChangeTeamServerCommand
            item.IsCheckable = True
            item.IsChecked = (svr Is Application.TFServer)
            ConnectMenu.Items.Add(item)
        Next
    End Sub

    ''' <summary>
    ''' Builds the List of work item types for a project
    ''' </summary>
    Private Sub BuildStoredQueryMenu()
        ' Clear existing menu items
        WorkItemQueryMenu.Items.Clear()
        If Not Application.SelectedProject Is Nothing Then
            For Each sq As StoredQuery In Application.SelectedProject.StoredQueries
                Dim item As MenuItem = New MenuItem()
                item.Header = sq.Name
                item.CommandParameter = sq
                item.IsCheckable = True
                item.IsChecked = (Application.SelectedStoredQuery Is sq)
                item.Command = SelectStoredQueryCommand
                WorkItemQueryMenu.Items.Add(item)
            Next
        Else
            Dim item As MenuItem = New MenuItem()
            item.Header = "You must first select a team project..."
            WorkItemQueryMenu.Items.Add(item)
        End If
    End Sub

    ''' <summary>
    ''' Builds the List of work item types for a project
    ''' </summary>
    Private Sub BuildProjectsMenu()
        ' Clear existing menu items
        ProjectsMenu.Items.Clear()
        If Not Application.TFServer Is Nothing AndAlso Application.TFServer.HasAuthenticated Then
            For Each p As Project In Application.WorkItemStore.Projects
                Dim item As MenuItem = New MenuItem()
                item.Header = p.Name
                item.CommandParameter = p
                item.Command = ChangeTeamProjectCommand
                item.IsCheckable = True
                item.IsChecked = (p Is Application.SelectedProject)
                ProjectsMenu.Items.Add(item)
            Next
        Else
            Dim item As MenuItem = New MenuItem()
            item.Header = "You must first connect to a team server..."
            ProjectsMenu.Items.Add(item)
        End If
    End Sub

    ''' <summary>
    ''' Builds the List of work item types for a project
    ''' </summary>
    Private Sub BuildDisplayByMenu()
        ' Clear existing menu items
        DisplayByMenu.Items.Clear()

        For Each e As Node.TreeType In [Enum].GetValues(GetType(Node.TreeType))
            Dim item As MenuItem = New MenuItem()
            item.Header = e.ToString
            item.CommandParameter = e
            item.Command = DisplayByCommand
            item.IsCheckable = True
            item.IsChecked = (e = Application.DisplayBy)
            DisplayByMenu.Items.Add(item)
        Next

    End Sub



#End Region

#Region " Command Handlers "

    ''' <summary>
    ''' Command handler for logo click event
    ''' </summary>
    Private Sub RDdotNet_MouseLeftButtonUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        ' Open the Vertigo website in the user's default browser
        System.Diagnostics.Process.Start("http://www.codeplex.com/TFSStickyBuddy")
    End Sub

#Region " ChangeTeamServer "

    Public Delegate Sub ChangeTeamServer_DoWorkHandler(ByVal server As TeamFoundationServer)
    Public Delegate Sub ChangeTeamServer_UIHandler(ByVal server As TeamFoundationServer, ByVal result As Boolean)

    Public Sub ChangeTeamServer_End(ByVal server As TeamFoundationServer, ByVal Result As Boolean)
        ' TODO: Suff to display everything
        ShowDetailsPane()
        BuildTeamServerMenu()
        BuildProjectsMenu()
        BuildStoredQueryMenu()
        RefreshData()
    End Sub

    Private Sub ChangeTeamServer_DoWork(ByVal server As TeamFoundationServer)
        WorkingUserControl.Update(Working.Actions.Start, "connecting to team server...", "connecting to team server...")
        Dim Result As Boolean = True
        Try
            WorkingUserControl.Update(Working.Actions.Progress, "authenticating team server...", "authenticating team server...")
            server.Authenticate()
            WorkingUserControl.Update(Working.Actions.Progress, "updating selected team server..", "authenticatication complete..")
            Application.TFServer = server
            WorkingUserControl.Update(Working.Actions.Progress, "", "Completed update of selected server...")
        Catch ex As Exception
            WorkingUserControl.Update(Working.Actions.Progress, ex.ToString, ex.Message)
            Result = False
        End Try
        WorkingUserControl.Update(Working.Actions.Stop, "", "Done...")
        Dim UpdateTeamServerUIHandler As ChangeTeamServer_UIHandler = New ChangeTeamServer_UIHandler(AddressOf ChangeTeamServer_End)
        Me.Dispatcher.BeginInvoke(DispatcherPriority.Normal, UpdateTeamServerUIHandler, server, Result)
    End Sub

    ''' <summary>
    ''' Command handler for changing the selected Team Server
    ''' </summary>
    Private Sub ChangeTeamServer_Start(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        HideWelcomeScreen()
        Dim tfs As TeamFoundationServer = CType(e.Parameter, TeamFoundationServer)
        ' Call Load ruteen on another thread
        Dim ltfsh As ChangeTeamServer_DoWorkHandler = New ChangeTeamServer_DoWorkHandler(AddressOf ChangeTeamServer_DoWork)
        ltfsh.BeginInvoke(tfs, Nothing, Nothing)
    End Sub

#End Region

    ''' <summary>
    ''' Command handler for changing the selected team project
    ''' </summary>
    Private Sub ChangeTeamProject(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Dim Project As Project = CType(e.Parameter, Microsoft.TeamFoundation.WorkItemTracking.Client.Project)
        Application.SelectedProject = Project
        Application.SelectedStoredQuery = Project.StoredQueries.Item(0)
        BuildProjectsMenu()
        BuildStoredQueryMenu()
        'TODO: Initiate refresh
        RefreshData()

    End Sub

    ''' <summary>
    ''' Command handler for changing the selected team project
    ''' </summary>
    Private Sub SelectStoredQuery(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Dim sq As StoredQuery = CType(e.Parameter, StoredQuery)
        If Application.SelectedStoredQuery Is sq Then
            Application.SelectedStoredQuery = Nothing
        Else
            Application.SelectedStoredQuery = sq
        End If
        BuildStoredQueryMenu()
        RefreshData()
    End Sub

    ''' <summary>
    ''' Command handler for changing the selected team project
    ''' </summary>
    Private Sub DisplayBy(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Dim tt As Node.TreeType = CType(e.Parameter, Node.TreeType)
        Application.DisplayBy = tt
        BuildDisplayByMenu()
        RefreshData()
    End Sub

    ''' <summary>
    ''' Command handler for ChangeSkinCommand
    ''' </summary>
    Private Sub ChangeSkin(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        Dim rd As ResourceDictionary = New ResourceDictionary()
        rd.MergedDictionaries.Add(CType(Application.LoadComponent(New Uri(CStr(e.Parameter), UriKind.Relative)), ResourceDictionary))
        Application.Current.Resources = rd

        ' save the skin setting
        My.Settings.Skin = CStr(e.Parameter)
        My.Settings.Save()

        ' TODO: Refresh bits that need refreshing
        ItemWrappers.OnContentChanged()
        'ItemInfoControl.OnSkinChanged()
    End Sub

#End Region

    ''' <summary>
    ''' Show the Welcome Screen user control and hides the other controls.
    ''' </summary>
    Private Sub ShowWelcomeScreen()
        HideDetailsPane()
        'DiagramControl.Visibility = Visibility.Hidden
        WelcomeUserControl.Visibility = Visibility.Visible
    End Sub


    '' <summary>
    '' Hides the Welcome Screen.
    '' </summary>
    Private Sub HideWelcomeScreen()
        WelcomeUserControl.Visibility = Visibility.Hidden
    End Sub

    ''' <summary>
    ''' Displays the details pane
    ''' </summary>
    Private Sub ShowDetailsPane()
        ' TODO: Any Edit or details panels
        ' Add the cloned column to layer 0:
        'If Not DiagramPane.ColumnDefinitions.Contains(column1CloneForLayer0) Then
        '    DiagramPane.ColumnDefinitions.Add(column1CloneForLayer0)
        'End If

        'if (family.Current != null)
        '    DetailsControl.DataContext = family.Current;
        'DetailsPane.Visibility = Visibility.Visible
        'DetailsControl.SetDefaultFocus()

        HideWelcomeScreen()

        ConnectMenu.IsEnabled = True
        SkinsMenu.IsEnabled = True
        ProjectsMenu.IsEnabled = True
        DisplayByMenu.IsEnabled = True
        WorkItemQueryMenu.IsEnabled = True
        SearchPanel.IsEnabled = True
    End Sub

    ''' <summary>
    ''' Hides the details pane
    ''' </summary>
    Private Sub HideDetailsPane()
        DetailsPane.Visibility = Visibility.Collapsed

        '' Remove the cloned columns from layers 0
        If DiagramPane.ColumnDefinitions.Contains(column1CloneForLayer0) Then
            DiagramPane.ColumnDefinitions.Remove(column1CloneForLayer0)
        End If

        ConnectMenu.IsEnabled = False
        SkinsMenu.IsEnabled = False
        ProjectsMenu.IsEnabled = False
        DisplayByMenu.IsEnabled = False
        WorkItemQueryMenu.IsEnabled = False
        SearchPanel.IsEnabled = False
    End Sub


    Private Sub ShowWorking_StoryboardCompleted(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub HideWorking_StoryboardCompleted(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub RefreshData()
        'TODO: Initiate refresh
        Dim Import As New TFSImport
        Import.Import(Application.ItemWrappers, Application.DisplayBy)
    End Sub

#Region " SearchText "

    Private Sub SearchText_MouseEnter(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles SearchText.MouseEnter
        If SearchText.Text = "[enter search]" Then
            SearchText.Text = ""
            SearchPanel.Opacity = 1
        End If
    End Sub

    Private Sub SearchText_MouseLeave(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles SearchText.MouseLeave
        If SearchText.Text = "[enter search]" Or SearchText.Text = "" Then
            SearchText.Text = "[enter search]"
            SearchPanel.Opacity = 0.5
        End If
    End Sub

#End Region


End Class
